<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Client -- 扫码登录页面</title>
</head>

<body>
  <div>
    扫码登录测试
  </div>
  <div>
    <button id="show-code-button">
      点我唤起扫码框
    </button>
    <button id="hide-code-button">
      点我关闭扫码框
    </button>
    <div id="code">
    </div>
  </div>

  <script>
    // DOM 元素
    const showCodeButton = document.getElementById("show-code-button")
    const codeContainer = document.getElementById("code")
    const hideCodeButton = document.getElementById("hide-code-button")

    // 必要的变量
    let uuid = null
    let codeWebsocket = null

    showCodeButton.addEventListener("click", () => {
      showCode()
    })

    hideCodeButton.addEventListener("click", () => {
      codeContainer.innerHTML = ""
    })

    // 展示扫码框
    const showCode = () => {
      // 建立 websocket 服务
      if (codeWebsocket) {
        codeWebsocket.close()
      }
      codeWebsocket = new WebSocket("ws://localhost:5000")
      codeWebsocket.onmessage = (e) => {
        console.log(e);
        const res = JSON.parse(e.data)
        const handlerFn = messageHandler[res.data.type]
        // 匹配到相应的函数，执行之
        if (typeof handlerFn === "function") {
          handlerFn(res)
        }
      }
      // 连接建立成功
      codeWebsocket.onopen = () => {
        // 发送消息，请求随机 id
        codeWebsocket.send("GET_CODE")
      }
    }

    // websocket 消息处理
    const messageHandler = {
      // 获得 codeId 接下来我们要生成二维码
      "CODE_ID": (res) => {
        const imgElement = document.createElement("img")
        uuid = res.data.uuid
        imgElement.src = `http://localhost:5000/login/login_qr_code/${uuid}`
        codeContainer.innerHTML = uuid
        codeContainer.appendChild(imgElement)
      },
      // 二维码被扫描，等待客户端确认
      "SCANNED": () => {
        codeContainer.innerHTML =
          `<div>
              <div>扫描成功，请点击确认按钮以登录</div>
             </div>`
      },
      // 登录成功，保存获得的 token
      "SUCCESS": () => {
        console.log("登录成功，在这里，开发者可以将 TOKEN 保存到 localstorage 中，然后执行用户相关的请求~")
        codeContainer.innerHTML =
          `<div>
              <div>登录成功~</div>
             </div>`
        codeWebsocket.close()
      }
    }
  </script>
</body>

</html>